package com.gr100.biz.api.shop;

import com.alibaba.fastjson.JSONArray;
import com.gr100.biz.api.shop.m.MActionHex;
import com.gr100.biz.api.shop.m.TaskM;
import com.gr100.biz.kit.FileKit;
import com.gr100.biz.plugin.document.Document;
import com.jfinal.log.Log;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by YFsoft on 16/3/16.
 */
public class ShopService {

    private static final Log logger = Log.getLog("ShopService");

    private Map<String,JSONArray> downloadAndParseDataFile(String key,String[] fileNames)
     throws MActionHex{

        Map<String,JSONArray> datas = new HashMap<String,JSONArray>();

        byte[] data = null;		//数据文件的二进制数据数组
        String tempFilePath = null;//缓存文件的存放目录

        try {
            data = Document.me().loadToMemory(key);
        } catch (IOException e) {
            throw new MActionHex("文件下载失败！"+e.getMessage());
        }

        //创建缓存文件，保存该临时文件
        File f = FileKit.createTempFile("zip");
        if(f!=null){
            FileKit.writeFile(f, data);
            //程序退出时自动删除
            f.deleteOnExit();
        }else{
            throw new MActionHex("创建临时文件失败！查看一下权限～");
        }

        tempFilePath = f.getAbsolutePath().replace(".zip", "");

        //解压数据文件
        FileKit.unZip(f, new File(tempFilePath));


        for(String fileName : fileNames){
            //读取json数据文件
            String tempStr = tempFilePath + File.separator + "json" + fileName + ".json";
            //将json文件转换成数据
            tempStr = FileKit.readFile(tempStr);
            if(null == tempStr){
                tempStr = "[]";
            }
            //解析成json对象
            JSONArray jsonArray = JSONArray.parseArray(tempStr);

            datas.put(fileName, jsonArray);
        }

        return datas;
    }


    public Map<String, Object> syncData(String key){
        Map<String, Object> m = new HashMap<String,Object>();

        final TaskM t = TaskM.create("SHOP_SYNC_DAY_DATA", key, "QINIU");
        if(t == null){
            m.put("errno", -20);
            m.put("code", "TASK CREATE ERROR!");
            return m;
        }
        m.put("errno", 0);
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("taskId", t.get("id"));
        m.put("data", data);
        new Thread(new Runnable(){

            @Override
            public void run() {

                logger.info("tag 1 ");
                Map<String,JSONArray> datas;
                String[] fileNames = new String[]{
                        "Order",
                        "OrderGroupPay",
                        "OrderProduct",
                        "ProductStock",
                        "PStockchangeDetail"
                };

                try {
                    datas = downloadAndParseDataFile(key,fileNames);

                } catch (MActionHex e) {
                    t.error(e.getMessage());
                    return;
                }

                logger.info("tag 2 ");
                try {
                    new ShopModel().syncData(datas);
                    logger.info("tag 3 ");
                } catch (Exception e) {
                    t.error(e.getMessage());
                    return;
                }
                //任务结束
                t.update(TaskM.FINISHED, null);
            }

        }).start();


        return m;
    }

    public Map<String, Object> syncDayData(String key){
        //1.
        Map<String, Object> m = new HashMap<String,Object>();

        final TaskM t = TaskM.create("SHOP_SYNC_DATA", key, "QINIU");
        if(t == null){
            m.put("errno", -20);
            m.put("code", "TASK CREATE ERROR!");
            return m;
        }
        m.put("errno", 0);
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("taskId", t.get("id"));
        m.put("data", data);
        new Thread(new Runnable(){

            @Override
            public void run() {

                logger.info("tag 1 ");
                Map<String,JSONArray> datas;
                String[] fileNames = new String[]{
                        "CheckStock",
                        "OverallDaliy",
                        "OverallDaliyDetail",
                        "PStockchangeDetail" //添加了一个需要同步的数据
                };

                try {
                    datas = downloadAndParseDataFile(key,fileNames);

                } catch (MActionHex e) {
                    t.error(e.getMessage());
                    return;
                }

                logger.info("tag 2 ");
                try {
                    new ShopModel().syncDayData(datas);
                    logger.info("tag 3 ");
                } catch (Exception e) {
                    t.error(e.getMessage());
                    return;
                }
                //任务结束
                t.update(TaskM.FINISHED, null);
            }

        }).start();


        return m;
    }

}
